package com.issac.vhr.service.task;

import com.issac.vhr.entity.Employee;
import com.issac.vhr.entity.MailConstants;
import com.issac.vhr.entity.Mail_send_log;
import com.issac.vhr.service.EmployeeService;
import com.issac.vhr.service.MailSendLogService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/*
* 去启动类加注解@EnableScheduling
*
* */
@Component
public class MailSendTask {

    @Autowired
    MailSendLogService mailSendLogService;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    EmployeeService employeeService;

    @Scheduled(cron = "0/10 * * * * ?")
    public void mailResendTask(){
        List<Mail_send_log> logs = mailSendLogService.getMailSendLogsByStatus();
        for (Mail_send_log mailSendLog : logs) {
            if (mailSendLog.getCount()>= MailConstants.MAX_TRY_COUNT){
                mailSendLogService.updateMailSendLogStatus(mailSendLog.getMsgId(),2);//重发3次 设置该条消息发送失败
            }else {
                //消息重发
                mailSendLogService.updateMailSendLogCount(mailSendLog.getMsgId(),new Date());
                Employee employee = employeeService.getEmployeeById(mailSendLog.getEmpId());
                rabbitTemplate.convertAndSend(MailConstants.MAIL_EXCHANGE_NAME,MailConstants.MAIL_ROUTING_KEY_NAME,employee,new CorrelationData(mailSendLog.getMsgId()));

            }
        }

    }

}
